package com.bawei.module_home.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_home.R
import com.bawei.module_home.databinding.ItemDeviceBinding
import com.bawei.module_home.model.DeviceModel

class DeviceAdapter:RecyclerView.Adapter<DeviceAdapter.DeviceViewHolder>() {
    val list = mutableListOf<DeviceModel>()

    // 定义点击回调接口
    interface OnItemClickListener {
        fun onItemClick(item: DeviceModel, position: Int)
    }
    interface OnItemLongClickListener {
        fun onItemLongClick(item: DeviceModel, position: Int)
    }
    var itemClickListener:OnItemClickListener? = null
    var itemLongClickListener:OnItemLongClickListener? = null
    // 设置点击监听器
    fun setOnItemClickListener(listener: DeviceAdapter.OnItemClickListener) {
        this.itemClickListener = listener
    }
    // 设置长按监听器
    fun setOnItemLongClickListener(listener: DeviceAdapter.OnItemLongClickListener) {
        this.itemLongClickListener = listener
    }
    fun setData(data:List<DeviceModel>){
        list.clear()
        list.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeviceViewHolder {
        val binding= ItemDeviceBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return DeviceViewHolder(binding)

    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: DeviceViewHolder, position: Int) {
        val item = list[position]
        val binding= DataBindingUtil.getBinding<ItemDeviceBinding>(holder.itemView) ?:return
        binding.device=item
        if (item.status=="正常"){
            binding.status.setTextColor(Color.parseColor("#22C55E"))
            binding.status.setBackgroundResource(R.drawable.device_status_background)
        }else{
            binding.status.setTextColor(Color.parseColor("#F97316"))
            binding.status.setBackgroundResource(R.drawable.device_status_background_other)
        }
        holder.itemView.setOnClickListener {
            itemClickListener?.onItemClick(item,position)
        }
        holder.itemView.setOnLongClickListener {
            itemLongClickListener?.onItemLongClick(item,position)
            true
        }

    }
    class DeviceViewHolder(item: ItemDeviceBinding): RecyclerView.ViewHolder(item.root){

    }
}
